package com.tubeonfire.model;

import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import com.tubeonfire.entity.Channel;

public class ChannelModel {

	static PersistenceManager pm = PMF.get().getPersistenceManager();

	public static void initPm() {
		if (pm.isClosed()) {
			pm = PMF.get().getPersistenceManager();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<Channel> all() {
		initPm();
		List<Channel> result = new ArrayList<Channel>();
		Query query = pm.newQuery(Channel.class);
		query.setRange(0, 10);
		result = (List<Channel>) query.execute();
		return result;
	}

	public static boolean add(Channel channel) {
		initPm();
		try {
			pm.makePersistent(channel);
		} catch (Exception e) {
			System.out.println("Error when add channel object.");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean addAll(List<Channel> listChannel) {
		initPm();
		try {
			pm.makePersistentAll(listChannel);
			System.out.println("Add all channels success.");
		} catch (Exception e) {
			System.out.println("Error when add many category object.");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean update(Channel channel) {
		initPm();
		pm.makePersistent(channel);
		return true;
	}

	@SuppressWarnings("unchecked")
	public static Channel getByAlias(String alias) {
		initPm();
		Channel channel = null;
		Query query = pm.newQuery(Channel.class);
		query.setFilter("alias==aliasPara");
		query.declareParameters("java.lang.String aliasPara");
		query.setRange(0, 1);
		List<Channel> listResult = (List<Channel>) query.execute(alias);
		if (listResult.size() > 0) {
			channel = listResult.get(0);
		}
		return channel;
	}

	public void closePM() {
		pm.close();
	}

}
